<template>
  <div class="app-container">
    <el-divider content-position="left"><div class="d-flex"><b class="color-primary mr12">分区类型</b><el-link type="primary" class="mr12" icon="el-icon-plus" @click="handleEdit({})">添加</el-link><el-link type="success" icon="el-icon-refresh" @click="handleRefresh(1)">刷新</el-link></div></el-divider>
    <el-table
      v-loading="loadingType"
      border
      stripe
      :data="gridTypes"
      style="width: 100%"
      size="small"
    >
      <el-table-column
        align="center"
        prop="id"
        label="id"
      />
      <el-table-column
        align="center"
        prop="name"
        label="名称"
      />
      <el-table-column
        align="center"
        prop="policy_type"
        label="决策类型"
      >
        <template #default="{row}">
          <el-tag v-if="row.policy_type === 1" type="primary">静态决策</el-tag>
          <el-tag v-if="row.policy_type === 2" type="success">动态决策</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="address"
        label="等级划分"
      >
        <el-table-column
          align="center"
          prop="address"
          label="等级"
        >
          <template #default="{row}">
            <span v-for="(item,index) in row.steps" :key="index" class="d-flex flex-column">{{ item.step }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="address"
          label="范围区间"
        >
          <template #default="{row}">
            <span v-for="(item,index) in row.steps" :key="index" class="d-flex flex-column">{{ item.lower + ' ~ ' + item.upper }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="address"
          label="颜色"
        >
          <template #default="{row}">
            <span v-for="(item,index) in row.steps" :key="index" class="color-black d-flex flex-column" :style="{background:item.color}">{{ item.color }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="address"
          label="默认等级"
        >
          <template #default="{row}">
            {{ row.steps.filter((val) => {
              return val.active > 0
            })[0].step }}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column
        align="center"
        prop="created_at"
        label="创建时间"
        width="160"
      />
      <el-table-column
        align="center"
        prop="created_at"
        label="默认"
        width="160"
      >
        <template #default="{row}">
          <i v-if="row.active > 0" class="color-success font20 el-icon-check" />
          <i v-else class="color-danger font20 el-icon-close" />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="address"
        label="操作"
        width="240"
      >
        <template #default="{row}">
          <el-link class="mr12" type="primary" icon="el-icon-edit" @click="handleEdit(row)">修改</el-link>
          <el-link class="mr12" type="success" icon="el-icon-check" @click="handleDefault(row)">设为默认</el-link>
          <el-link type="danger" icon="el-icon-delete" @click="handleDelete(row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <div class="h12" />
    <el-divider content-position="left"><div class="d-flex"><b class="color-primary mr12">分区管理</b><el-link type="success" icon="el-icon-refresh" @click="handleRefresh(2)">刷新</el-link></div></el-divider>
    <el-table
      v-loading="loadingGrids"
      border
      stripe
      :data="grids"
      style="width: 100%"
      size="small"
    >
      <el-table-column
        align="center"
        prop="id"
        label="id"
      />
      <el-table-column
        align="center"
        prop="gridType.policy_type"
        label="决策类型"
      >
        <template #default="{row}">
          <el-tag v-if="row.gridType.policy_type === 1" type="primary">静态决策</el-tag>
          <el-tag v-if="row.gridType.policy_type === 2" type="success">动态决策</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="gridType.name"
        label="决策方式"
      />
      <el-table-column
        align="center"
        prop="valid"
        label="是否生效"
      >
        <template #default="{row}">
          <i v-if="row.valid > 0" class="color-success font20 el-icon-check" />
          <i v-else class="color-danger font20 el-icon-close" />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="created_at"
        label="创建时间"
      />
      <el-table-column
        align="center"
        prop="address"
        label="操作"
        width="240"
      >
        <template #default="{row}">
          <el-link class="mr12" type="primary" icon="el-icon-document" @click="handleDetail(row)">详情</el-link>
          <el-link type="success" icon="el-icon-check" @click="handleValid(row)">设为生效分区</el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="设置分区类型"
      :visible.sync="dialogVisible"
      width="800px"
      @close="dialogClose"
    >
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="名称" clearable />
        </el-form-item>
        <el-row>
          <el-col :span="12"><el-form-item label="决策类型" prop="policy_type">
            <el-select v-model="formData.policy_type" placeholder="决策类型" filterable>
              <el-option v-for="(item,index) in policyTypes" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="灌水定额" prop="irri_quota">
            <el-input v-model="formData.irri_quota" type="number" placeholder="灌水定额" clearable>
              <template slot="append">mm</template>
            </el-input>
          </el-form-item></el-col>
        </el-row>
        <el-form-item label="等级设定" prop="steps">
          <el-table
            border
            :data="formData.steps"
            style="width: 100%"
          >
            <el-table-column
              align="center"
              prop="date"
              label="等级"
              width="120"
            >
              <template #default="{row}">
                <el-input v-model="row.step" type="number" placeholder="等级" clearable style="text-align:center;" />
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="name"
              label="下限"
            >
              <template #default="{row}">
                <el-input v-model="row.lower" type="number" placeholder="下限" clearable />
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="address"
              label="上限"
            >
              <template #default="{row}">
                <el-input v-model="row.upper" type="number" placeholder="上限" clearable />
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="address"
              label="颜色"
            >
              <template #default="{row}">
                <el-color-picker v-model="row.color" />
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="address"
              label="默认"
              width="100"
            >
              <template #default="{row,$index}">
                <el-switch v-model="row.active" :active-value="1" :inactive-value="0" @change="changeActive(row,$index)" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分区详情"
      :visible.sync="dialogDetailVisible"
      width="900px"
      top="4vh"
    >
      <el-descriptions border label-class-name="labelClass" content-class-name="contentClass">
        <el-descriptions-item label="决策类型">
          <el-tag v-if="grid.gridType && grid.gridType.policy_type === 1" type="primary">静态决策</el-tag>
          <el-tag v-if="grid.gridType && grid.gridType.policy_type === 2" type="success">动态决策</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="决策方式">{{ grid.gridType && grid.gridType.name }}</el-descriptions-item>
        <el-descriptions-item label="是否生效">
          <el-tag v-if="grid.valid" type="success">生效</el-tag>
          <el-tag v-else type="danger">未生效</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建者">{{ grid.created_user }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ grid.created_at }}
        </el-descriptions-item>
      </el-descriptions>
      <div class="h12" />
      <div style="width:100%;height:680px;">
        <l-map
          :zoom="zoom"
          :center="center"
          :options="options"
        >
          <l-tile-layer v-for="(item,index) in urls" :key="index" :url="item" />
          <l-polygon
            v-for="(item,index) in grid.gridDetail"
            :key="'map' + index"
            :lat-lngs="item.latlngs"
            :fill-color="item.color"
            :fill-opacity="60"
            :weight="1"
            color="#fff"
          />
        </l-map></div>
    </el-dialog>
  </div>
</template>

<script>
import { getAll as getGridTypes, addOne, updateOne, deleteOne, defaultOne } from '@/api/gridType'
import { getAll as getGrids, defaultOne as defaultGrid, getOne as getGrid } from '@/api/grid'
import { mapGetters } from 'vuex'
import { convertArr2Obj } from '@/utils'
import map from '@/config/map'
export default {
  data() {
    return {
      gridTypes: [],
      grids: [],
      loadingType: false,
      loadingGrids: false,
      policyTypes: [{ label: '静态决策', value: 1 }, { label: '动态决策', value: 2 }],
      formData: {
        name: '',
        policy_type: '',
        irri_quota: '',
        steps: [
          { step: 1, lower: '', upper: '', color: '#b7ecef', active: 0 },
          { step: 2, lower: '', upper: '', color: '#1e82e0', active: 1 },
          { step: 3, lower: '', upper: '', color: '#09098f', active: 0 }
        ]
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        policy_type: [
          { required: true, message: '请选择决策类型', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      grid: {},
      dialogDetailVisible: false,
      zoom: map.zoom,
      center: map.center,
      options: map.options,
      urls: map.mapTypes[map.initType]
    }
  },
  computed: {
    ...mapGetters(['project', 'fields']),
    field() {
      const idx = this.fields.findIndex((val) => {
        return +val.project_id === this.project.id
      })
      return this.fields[idx]
    },
    policyTypesObj() {
      return convertArr2Obj(this.policyTypes, 'value')
    }
  },
  created() {
    this.getGridTypes()
    this.getGrids()
    this.center = [this.field.longitude, this.field.latitude]
    this.zoom = this.project.maplevel
  },
  methods: {
    async getGridTypes() {
      this.loadingType = true
      const { data: { data }} = await getGridTypes({ field_id: this.field.id })
      this.gridTypes = data
      this.loadingType = false
    },
    async getGrids() {
      this.loadingGrids = true
      const { data: { data, total }} = await getGrids({ field_id: this.field.id })
      this.grids = data
      this.gridsTotal = total
      this.loadingGrids = false
    },
    handleRefresh(num) {
      if (num === 1) {
        this.getGridTypes({ field_id: this.field.id })
      } else {
        this.getGrids({ field_id: this.field.id })
      }
    },
    changeActive(row, index) {
      const active = row.active
      if (this.formData.steps.filter((val) => {
        return val.active === 1
      }).length === 0) {
        this.$message.error('等级设定中必须有一个默认值')
        this.formData.steps[index].active = 1
        return
      }
      this.formData.steps = this.formData.steps.map((item, idx) => {
        item.active = 0
        if (active && index === idx) {
          item.active = 1
        }
        return item
      })
    },
    dialogClose() {
      this.formData = {
        name: '',
        policy_type: '',
        irri_quota: '',
        steps: [
          { step: 1, lower: '', upper: '', color: '#b7ecef', active: 0 },
          { step: 2, lower: '', upper: '', color: '#1e82e0', active: 1 },
          { step: 3, lower: '', upper: '', color: '#09098f', active: 0 }
        ]
      }
    },
    handleEdit(row) {
      if (row.id) {
        this.formData = row
      }
      this.dialogVisible = true
    },
    submit() {
      this.$refs['ruleForm'].validate(async(valid) => {
        if (valid) {
          if (this.formData.id) {
            const { msg } = await updateOne(this.formData.id, this.formData)
            this.$message.success(msg)
          } else {
            this.formData.field_id = this.field.id
            const { msg } = await addOne(this.formData)
            this.$message.success(msg)
          }
          this.dialogVisible = false
          this.getGridTypes()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleDefault(row) {
      this.$confirm('确定要将此分区类型设置为默认分区类型吗？', '操作确认', { type: 'warning' }).then(async() => {
        const { msg } = await defaultOne(row.id)
        this.$message.success(msg)
        this.getGridTypes()
      }).catch(() => {})
    },
    async handleDelete(row) {
      this.$confirm('确定要删除此分区方式吗？', '操作确认', { type: 'warning' }).then(async() => {
        const { msg } = await deleteOne(row.id)
        this.$message.success(msg)
        this.getGridTypes()
      }).catch(() => {})
    },
    async handleDetail(row) {
      const { data } = await getGrid(row.id)
      this.grid = data
      this.dialogDetailVisible = true
    },
    handleValid(row) {
      this.$confirm('确定要将此分区设置为默认分区吗？', '操作确认', { type: 'warning' }).then(async() => {
        const { msg } = await defaultGrid(row.id)
        this.$message.success(msg)
        this.getGrids()
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
